import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'

const useAuthStore = create(
    devtools(
        persist(
            (set) => ({
                token: null,
                userInfo: null,
                menus: [],

                // 设置登录信息
                setAuth: (token, userInfo) => set({
                    token,
                    userInfo,
                }),

                // 清除登录信息
                clearAuth: () => {
                    set({
                        token: null,
                        userInfo: null,
                    });
                },

                // 设置菜单
                setMenus: (menus) => set({
                    menus
                }),
            }),
            {
                name: 'auth-storage',
                storage: {
                    getItem: (name) => {
                        const item = sessionStorage.getItem(name);
                        return item ? JSON.parse(item) : null;
                    },
                    setItem: (name, value) => {
                        sessionStorage.setItem(name, JSON.stringify(value));
                    },
                    removeItem: (name) => {
                        sessionStorage.removeItem(name);
                    },
                },
            }
        )
    )
)

export default useAuthStore